local Msg = require("core.Msg")
local LimitBuyExcel = require("excel.DateActivity").limitBuy
local Grid = require("bag.Grid")
local ObjHuman = require("core.ObjHuman")
local BagLogic = require("bag.BagLogic")
local Broadcast = require("broadcast.Broadcast")
local Lang = require("common.Lang")
local DateActFL = require("activity.DateActFL")
local HtmlUtil = require("common.HtmlUtil")
local Log = require("common.Log")
local ShopHelp = require("shop.ShopHelp")
local ActDefine = require("activity.Define")

function open(human, id, type, num, type1)
  local sendMsg = Msg.gc.GC_DATE_LIMIT_BUY
  local activityNum = DateActFL.onGetCurActRuleID(id)  
  local activity = LimitBuyExcel[activityNum]
  if not activity then
    return
  end
  sendMsg.info[0] = #activity.isShow
  local cache = {}
  for i=1,#activity.isShow do
    sendMsg.info[i].isShow = activity.isShow[i]
    sendMsg.info[i].limitCnt = activity.limitCnt[i]
    Grid.create(cache, activity.reward[i][1], activity.reward[i][2])
    Grid.makeItem(cache, sendMsg.info[i].reward, 0, human)
    sendMsg.info[i].buyCnt = human.db.DateLimitBuyTimes[i - 1]
    sendMsg.info[i].oldPrice = activity.oldPrice[i]
    sendMsg.info[i].newPrice = activity.newPrice[i]
    sendMsg.info[i].activityId = 0
    sendMsg.info[i].isWorth = activity.isWorth[i]
    sendMsg.info[i].salesCnt = 0
  end  
  sendMsg.type = 1
  Msg.send(sendMsg, human.fd)
end

function getReward(human, id, index)
  local activityNum 
  activityNum = DateActFL.onGetCurActRuleID(id)
  local activity = LimitBuyExcel[activityNum]
  if not activity then
    return
  end
  if activity.limitCnt[index] - human.db.DateLimitBuyTimes[index-1] <= 0 then
    return
  end
  
  if ObjHuman.getYuanbao(human) < activity.newPrice[index] then    
    return ShopHelp.onNoRMB(human)
  end
  
  if not BagLogic.checkCanAddItem(human, activity.reward[index][1], 1, activity.reward[index][2]) then
    return Broadcast.sendBroadcast(human, Lang.DOWN, Lang.YUNYING_BAG_NOT_ENOUGH)
  end

  human.db.DateLimitBuyTimes[index-1] = human.db.DateLimitBuyTimes[index-1] + 1 
  ObjHuman.decYuanbao(human, activity.newPrice[index], "dateactholidaygift")
  BagLogic.addItem(human, activity.reward[index][1], 1, activity.reward[index][2], "dateactholidaygift")

  open(human, id)
  local cache = {}
  Grid.create(cache, activity.reward[index][1], activity.reward[index][2])
  local str = string.format(Lang.DATE_LIMIT_BUY_BRO, HtmlUtil.fontName(human.name, human._id), HtmlUtil.fontItem(cache), human._id)
  Broadcast.sendBroadcast2World(Lang.UP + Lang.GROSSIP, str)
  Log.write(Log.LOGID_OSS_YUNYING_LIMIT_BUY, human._id, human.account, human.name,human.db.lv, activity.reward[index][1], activity.reward[index][2])
end

function onEnd()
  for _,human in pairs(ObjHuman.onlineUuid) do
    for i=0, 39 do
      human.db.DateLimitBuyTimes[i - 1] = 0
    end
  end
end

DateActFL.onRegisterCallBack(ActDefine.OPERATEACT_TYPE_LIMITBUY, nil, nil, onEnd, nil)